//
//  LZFTuiJianTagVC.m
//  LZFBuDieJie
//
//  Created by 梁梓烽 on 16/7/19.
//  Copyright © 2016年 liangzifeng. All rights reserved.
//

#import "LZFTuiJianTagVC.h"
#import "LZFCategoryCell.h"
#import "LZFTuiJianUserCell.h"
#import <AFNetworking.h>
#import <MJExtension.h>
#import <MJRefresh.h>
#import "LZFCateoryItem.h"
#import "LZFTuiJianUserItem.h"
#import <SVProgressHUD.h>
#import "LZFCategoryCell.h"
#import "LZFTuiJianUserCell.h"

//加载数据的url挂掉了

/** 拿到类别tableview当前被选中的cell的行号 */
#define categoryTableViewSelectedRow  self.categoryTableView.indexPathForSelectedRow.row
/** 拿到类别tableview当前被选中的cell对应的模型 */
#define  categoryTableViewSelectedItem  (self.categoriesArray[categoryTableViewSelectedRow])
@interface LZFTuiJianTagVC ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *categoryTableView;
@property (weak, nonatomic) IBOutlet UITableView *userTableView;

@property(nonatomic,weak)AFHTTPSessionManager *manager;

@property(nonatomic,strong)NSMutableArray<LZFCateoryItem *> *categoriesArray;

@end

@implementation LZFTuiJianTagVC


#pragma mark -懒加载
-(AFHTTPSessionManager *)manager
{
    if (_manager==nil) {
        _manager=[AFHTTPSessionManager manager];
    }
    return _manager;
}


-(NSMutableArray *)categoriesArray
{
    if (_categoriesArray==nil) {
        _categoriesArray=[NSMutableArray new];
    }
    return _categoriesArray;
}


#pragma mark -viewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];
   
    //导航条设置
    [self setUpNav];
    
    //设置tableivew
    [self setUpTableView];
    
    //设置userTableView的刷新控件
    [self setUpFresh];
    
    //加载左边的category
    [self loadCategory];
    
    
}

#pragma mark -初始化设置

static NSString * const categoryID=@"catetoryID";
static NSString * const tuiJIanUserID=@"tuiJIanUserID";
-(void)setUpNav
{
    self.title=@"推荐关注";
}

-(void)setUpTableView
{
    self.automaticallyAdjustsScrollViewInsets=NO;
    
    //categotyTableView
    self.categoryTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    self.categoryTableView.contentInset=UIEdgeInsetsMake(LZFNavMaxY, 0, 0, 0);
    //注册cell
    [self.categoryTableView registerNib:[UINib nibWithNibName:NSStringFromClass([LZFCategoryCell class]) bundle:nil] forCellReuseIdentifier:categoryID];
    
    
    //userTableView
    self.userTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    self.userTableView.contentInset=UIEdgeInsetsMake(LZFNavMaxY, 0, 0, 0);
    //注册cell
    [self.categoryTableView registerNib:[UINib nibWithNibName:NSStringFromClass([LZFCategoryCell class]) bundle:nil] forCellReuseIdentifier:tuiJIanUserID];

}

-(void)setUpFresh
{
    self.userTableView.mj_header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];

    self.userTableView.mj_footer=[MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];

}

#pragma mark -网络请求
-(void)loadCategory
{
    //取消当前session里的所有任务
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    NSMutableDictionary *params=[NSMutableDictionary new];
    params[@"a"] = @"category";
    params[@"c"] = @"subscribe";

    
    //弹框
    [SVProgressHUD show];
    
    WeakSelf
    [self.manager GET:LZFRequestURL parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [SVProgressHUD dismiss];
        //字典转模型
        weakSelf.categoriesArray=[LZFCategoryCell mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        //刷新类别表格
        [weakSelf.categoryTableView reloadData];
        
        
        //让类别表格默认选中第一个行
        [weakSelf.categoryTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionTop];
        
        
        //让userTableView进入下拉刷新
        [weakSelf.userTableView.mj_header beginRefreshing];
    
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        LZFLog(@"%@",error);
        
        [SVProgressHUD dismiss];
    }];
    
    
    
    
}

//下拉加载新数据
-(void)loadNewData
{
    //取消当前session里的所有任务
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    NSMutableDictionary *params=[NSMutableDictionary new];
    params[@"a"] = @"category";
    params[@"c"] = @"subscribe";
    
 
    LZFCateoryItem *selelctedCategoryItem=self.categoriesArray[categoryTableViewSelectedRow];
      params[@"category_id"] = selelctedCategoryItem.ID;
    
    
    WeakSelf
    [self.manager GET:LZFRequestURL parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
      
        //下拉更新的话,设置为第一个页
        selelctedCategoryItem.page=1;
        
        //记录用户数的总数
        selelctedCategoryItem.total=responseObject[@"total"];
        
        //字典转模型
        selelctedCategoryItem.user=[LZFTuiJianUserItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        //刷新类别表格
        [self.userTableView reloadData];
        
        //结束刷新
        [self.userTableView.mj_header endRefreshing];
        
    
        //判断是否隐藏uerTableView的footer控件
        if (selelctedCategoryItem.user.count>[selelctedCategoryItem.total intValue]) {
            //表示一次就已经加载完服务器返回的总用户数
            self.userTableView.mj_footer.hidden=YES;
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
        //结束刷新
        [self.userTableView.mj_header endRefreshing];
        
       
    }];
    
    
    
    
}

//上拉加载更多数据
-(void)loadMoreData
{
    //取消当前session里的所有任务
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    NSMutableDictionary *params=[NSMutableDictionary new];
    params[@"a"] = @"category";
    params[@"c"] = @"subscribe";
    
    NSInteger row= self.categoryTableView.indexPathForSelectedRow.row;
    LZFCateoryItem *selelctedCategoryItem=self.categoriesArray[row];
    params[@"category_id"] = selelctedCategoryItem.ID;
    
     NSInteger page=selelctedCategoryItem.page+1;
    params[@"page"] = @(page);
    
    
    WeakSelf
    [self.manager GET:LZFRequestURL parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //下拉更新的话,设置为第一个页
        selelctedCategoryItem.page=page;
        
        //记录用户数的总数
        selelctedCategoryItem.total=responseObject[@"total"];
        
        //字典转模型 ,追加数组
        NSArray *newUser=[LZFTuiJianUserItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];;
        [selelctedCategoryItem.user addObjectsFromArray:newUser];
        
    
        //刷新类别表格
        [self.userTableView reloadData];
        
        
        //判断是否隐藏uerTableView的footer控件
        if (selelctedCategoryItem.user.count>[selelctedCategoryItem.total intValue]) {
            //表示一次就已经加载完服务器返回的总用户数,隐藏加载更多数据的控件
            self.userTableView.mj_footer.hidden=YES;
        }
        else
        {
            //结束尾部刷新
            [self.userTableView.mj_footer endRefreshing];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //结束刷新
        [self.userTableView.mj_footer endRefreshing];
        
    }];

}


#pragma mark -uitableviewdatasource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView==self.categoryTableView) {
        //catetoryTableView
        return self.categoriesArray.count;
    }
    else
    {
        //userTableVIew
        NSInteger row= self.categoryTableView.indexPathForSelectedRow.row;
        LZFCateoryItem *selectedCategoryItem=self.categoriesArray[row];
        return selectedCategoryItem.user.count;
        
    }

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        
        if (tableView==self.categoryTableView) {
            //catetoryTableView
            
            LZFCategoryCell *categoryCell=[tableView dequeueReusableCellWithIdentifier:categoryID];
           //给模型
            LZFCateoryItem *categoryItem= self.categoriesArray[indexPath.row];

            categoryCell.categoryItem=categoryItem;
            
            return categoryCell;
        }
        else
        {
            //userTableVIew
            LZFTuiJianUserCell *tuiJIanUserCell=[tableView dequeueReusableCellWithIdentifier:tuiJIanUserID];
            
            LZFTuiJianUserItem *tuiJianUserItem= categoryTableViewSelectedItem.user[indexPath.row];

            tuiJIanUserCell.tuiJIanUserItem=tuiJianUserItem;
            
            return tuiJIanUserCell;
        }
        
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView==self.categoryTableView) {
        //catetoryTableView
        LZFCateoryItem *selectedCategoryItem=categoryTableViewSelectedItem;
        
        [self.userTableView reloadData];
        
        if (selectedCategoryItem.user.count>[selectedCategoryItem.total intValue]) {
            self.userTableView.mj_footer.hidden=YES;
        }
        
        if (selectedCategoryItem.user.count==0) {
            [self.userTableView.mj_header beginRefreshing];
        }
    
}
    else
    {
        //userTableVIew
        LZFLog(@"点击了右边的%zd行",indexPath.row);
    }

    
    
}













@end
